﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using SCSService;
using SCS.Core.Models;
using SCS.Core.ViewModels;
using System.Web;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace SCS.Core.Controllers
{
    public class AdvantageSettingController : BaseController
    {
        public ActionResult Index()
        {
            return RedirectToAction("ListMenu");
        }
        #region Support -Duc
        #region Load Category Product
        public StringBuilder GetListTypeProductBuilder(int? id, int LanguageID, int siteGuid)
        {
            StringBuilder sb = new StringBuilder();
            return ListTypeProductBuilder(ref sb, id, true, LanguageID, siteGuid);
        }

        public StringBuilder ListTypeProductBuilder(ref StringBuilder sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Type_Product> listType = Models.StockModel.GetListTypeProductByParentId(id, LanguagesID, siteGuid);
            if (root)
            {
                sb.Append("<ul id='navigation' class='treeview'> <a href='#' onclick=WriteURL('/Product/ListProduct')>" + "Danh sách Sản phẩm"+"</a>");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listType)
            {
                sb.Append("<li>--<a href='#' onclick=WriteURL('/Product/ListProduct/" + item.TypeProductID + "')>" + item.TypeProductName + "</a>");
                List<SCSService.Type_Product> listChild = Models.StockModel.GetListTypeProductByParentId(item.TypeProductID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListTypeProductBuilder(ref sb, item.TypeProductID, false, LanguagesID, siteGuid);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }
        #endregion
        #region Load ListArticleCategory
        public StringBuilder GetListArticleCategoryBuilder(int? id, int LanguageID, int siteGuid)
        {
            StringBuilder sb = new StringBuilder();
            return ListArticleCategoryBuilder(ref sb, id, true, LanguageID, siteGuid);
        }

        public StringBuilder ListArticleCategoryBuilder(ref StringBuilder sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Article_Category> listcate = Models.ArticaleMasterModel.GetListArticleCategoryByParentId(id, LanguagesID, siteGuid);
            if (root)
            {
                sb.Append("<ul id='navigation' class='treeview'><a href='#' onclick=WriteURL('/Article/ListArticles') >" + "Chuyên mục tin tức " + "</a>");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listcate)
            {
                sb.Append("<li>--<a href='#' onclick=WriteURL('/Article/ListArticles/" + item.CategoriesID + "')>" + item.CategoriesName + "</a>");
                List<SCSService.Article_Category> listChild = Models.ArticaleMasterModel.GetListArticleCategoryByParentId(item.CategoriesID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListArticleCategoryBuilder(ref sb, item.CategoriesID, false, LanguagesID, siteGuid);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }
        #endregion
        #region Load StaticArticleCategory
        public StringBuilder GetListStaticArticleCategoryBuilder(int? id, int LanguageID, int siteGuid)
        {
            StringBuilder sb = new StringBuilder();
            return ListStaticArticleCategoryBuilder(ref sb, id, true, LanguageID, siteGuid);
        }

        public StringBuilder ListStaticArticleCategoryBuilder(ref StringBuilder sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Artilce_Static_Category> listcate = Models.ArticaleMasterModel.GetListStaticArticleCategoryByParentId(id, LanguagesID, siteGuid);
            if (root)
            {
                sb.Append("<ul id='navigation' class='treeview'><a href='#' onclick=WriteURL('/Article/ListArticlesStatic') >" + "Danh sách nội dung" + "</a>");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listcate)
            {
                sb.Append("<li> --<a href='#' onclick=WriteURL('/Article/ListArticlesStatic/" + item.StaticCategoryID + "')>" + item.StaticCategoryName + "</a>");
                List<SCSService.Artilce_Static_Category> listChild = Models.ArticaleMasterModel.GetListStaticArticleCategoryByParentId(item.StaticCategoryID, LanguagesID, siteGuid);
                if (listChild.Count() > 0)
                {
                    ListStaticArticleCategoryBuilder(ref sb, item.StaticCategoryID, false, LanguagesID, siteGuid);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }
        #endregion
        public ActionResult DetailSupport()
        {
            var typeSupport = new Models.Collection.TypeSupportCollection();
            int siteGuid = GetSiteGuid();

            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());

            ViewData["IsAdd"] = true;
            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", languageId);

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailSupport", typeSupport);

        }
        public ActionResult DeleteSupport(int id, FormCollection collection)
        {
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            Models.ConfigModel.DeleteSupport(id);
            ViewData["Result"] = "Delete success!";


            return Redirect("/" + DefaultSiteGuidGetter() + "/" + StockModel.GetLanguageByID(languageId).countryCode + "/AdvantageSetting/ListSupport");
        }
        public ActionResult SaveAddSupport(FormCollection collection)
        {
            var typeSupport = new Models.Collection.TypeSupportCollection();
            TryUpdateModel(typeSupport);
            int typeId = 0;
            try
            {

                //Create Type Product
                SCSService.Support type = new Support();
                type.SupportName = typeSupport.SupportName;
                type.SupportText = typeSupport.SupportText;
                type.SupportType = typeSupport.SupportType;
                type.SupportActive = typeSupport.SupportActive; //is active
                type.SupportAccount = typeSupport.SupportAccount;
                type.LanguagesID = typeSupport.LanguagesID;
                type.Sort = typeSupport.Sort;
                type.SiteGuid = DefaultSiteGuidGetter();
                typeId = Models.ConfigModel.CreateSupport(type);

                ViewData["Result"] = "Create support Success!";

            }
            catch
            {
                return View("DetailSupport", typeSupport);
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + StockModel.GetLanguageByID(int.Parse(collection.Get("LanguagesID"))).countryCode + "/AdvantageSetting/ListSupport");
        }
        public ActionResult ListSupport(string SupportNameSearch, bool? SupportActiveSearch, int? SortSearch, string PhoneSearch, string EmailSearch)
        {

            int currentPage = 1;
            int pageSize = 20;
            string sortField = "SupportName";
            string sortDirection = "Asc";

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListSupport(SupportNameSearch, SupportActiveSearch, SortSearch, PhoneSearch, EmailSearch, currentPage, pageSize, sortField, sortDirection, null, siteGuid);
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListSupport(string SupportNameSearch, bool? SupportActiveSearch, int? SortSearch, string PhoneSearch, string EmailSearch, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 20;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;

            var query = ConfigModel.GetListSupport(SupportNameSearch, SupportActiveSearch, LanguageID, SortSearch, siteGuid).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Support), "SupportName");
                var sortExpression = Expression.Lambda<Func<Support, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Support>();


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
            {
                var ViewModels = new SupportViewModels()
                {

                    SupportItem = result

                };
                return View(ViewModels);
            }
        }


        public ActionResult EditSupport(int id)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();


            var support = Models.ConfigModel.GetListSupportById(id, LanguageID, siteGuid);
            var typesupport = new Models.Collection.TypeSupportCollection();
            typesupport.SupportID = id;
            typesupport.SupportAccount = support.SupportAccount;
            typesupport.SupportActive = support.SupportActive;
            typesupport.SupportName = support.SupportName;
            typesupport.SupportText = support.SupportText;
            typesupport.SupportType = support.SupportType;
            typesupport.Sort = support.Sort;
            typesupport.SiteGuid = support.SiteGuid;
            typesupport.LanguagesID = support.LanguagesID;
            ViewData["IsAdd"] = false;
            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", LanguageID);
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailSupport", typesupport);
        }
        public ActionResult SaveEditSupport(FormCollection collection)
        {
            var typeSupport = new Models.Collection.TypeSupportCollection();
            TryUpdateModel(typeSupport);
            int typeId = 0;
            try
            {

                //Create Type Product
                SCSService.Support type = new Support();
                type.SupportID = typeSupport.SupportID;
                type.SupportName = typeSupport.SupportName;
                type.SupportText = typeSupport.SupportText;
                type.SupportType = typeSupport.SupportType;
                type.SupportActive = typeSupport.SupportActive; //is active
                type.SupportAccount = typeSupport.SupportAccount;
                type.LanguagesID = typeSupport.LanguagesID;
                type.Sort = typeSupport.Sort;
                type.SiteGuid = DefaultSiteGuidGetter();
                Models.ConfigModel.UpdateSupport(type);

                ViewData["Result"] = "Create support Success!";

            }
            catch
            {
                return View("DetailSupport", new SCSService.Support());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + StockModel.GetLanguageByID(int.Parse(collection.Get("LanguagesID"))).countryCode + "/AdvantageSetting/ListSupport");


        }
        #endregion

        #region "Menu Manage"
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult AddMenu()
        {
            var menu = new Models.Collection.MenuCollection();
            menu.Active = true;
            int siteGuid = GetSiteGuid();
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            ViewData["ListTyproduct"] = GetListTypeProductBuilder(null, languageId, siteGuid);
            ViewData["ListArticleCategory"] = GetListArticleCategoryBuilder(null, languageId, siteGuid);
            ViewData["ListStaticArticleCategory"] = GetListStaticArticleCategoryBuilder(null, languageId, siteGuid);
            ViewData["IsAdd"] = true;
            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", languageId);
            ViewData["ListParent"] = new SelectList(GetListMenuDropBasic(null, null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "MenuId", "MenuText");

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailMenu", menu);      ///Return to view detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAdd(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            var menu = new Models.Collection.MenuCollection();
            TryUpdateModel(menu);
            int menuID = 0;
            try
            {

                //Create Menu
                SCSService.Menu menus = new Menu();
                menus.MenuName = menu.MenuName;
                menus.MenuText = menu.MenuText;
                menus.MenuUrl = menu.MenuUrl;
                if (menu.Images != null)
                {
                    menus.Images = menu.Images;
                }
                if (menu.SortOrder == null)
                {
                    menus.SortOrder = Models.ConfigModel.GetCountMenu(LanguageID, GetSiteGuid()) + 1;
                }
                else
                {
                    menus.SortOrder = (int)menu.SortOrder;
                }
                menus.LanguagesID = Models.StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()); //menu.LanguagesID;
                menus.SiteGuid = DefaultSiteGuidGetter();
                menus.MenuStatus = menu.Active==true?(byte)1:(byte)0;
                menus.PartnerMenuId = menu.PartnerMenuId;
                
                menuID = Models.ConfigModel.CreateMenu(menus);

                ViewData["Result"] = "Create Menu Success!";

            }
            catch
            {
                return View("DetailMenu", new Models.Collection.MenuCollection());     //return to detail
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/AdvantageSetting/ListMenu/");
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult EditMenu(int id)
        {
            ViewData["IsAdd"] = false;
            int siteGuid = GetSiteGuid();
            int languageId = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            ViewData["ListTyproduct"] = GetListTypeProductBuilder(null, languageId, siteGuid);
            ViewData["ListArticleCategory"] = GetListArticleCategoryBuilder(null, languageId, siteGuid);
            ViewData["ListStaticArticleCategory"] = GetListStaticArticleCategoryBuilder(null, languageId, siteGuid);
            Menu menu = Models.ConfigModel.GetMenuByID(id);
            var me = new Models.Collection.MenuCollection();
            me.MenuId = menu.MenuId;
            me.MenuName = menu.MenuName;
            me.MenuText = menu.MenuText;
            me.MenuUrl = menu.MenuUrl;
            me.Images = menu.Images;
            if (menu.MenuStatus != null)
            {
                me.Active = menu.MenuStatus==1?true:false;
            }

            if (menu.LanguagesID != null)
            {
                me.LanguagesID = menu.LanguagesID;
            }

            if (menu.PartnerMenuId != null)
            {
                me.PartnerMenuId = menu.PartnerMenuId;
            }

            me.SortOrder = menu.SortOrder;
            me.SiteGuid = menu.SiteGuid;
            

            ViewData["ListLanguage"] = new SelectList(Models.StockModel.GetListLanguage(), "LanguagesID", "countryName", menu.LanguagesID != null ? menu.LanguagesID : 0);
            ViewData["ListParent"] = new SelectList(GetListMenuDropBasic(null, null, null, null, null, null, null, null, StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter()), siteGuid), "MenuId", "MenuText", menu.PartnerMenuId != 0 ? menu.PartnerMenuId : 0);
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailMenu", me);      ///return to detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEdit(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            var menu = new Models.Collection.MenuCollection();
            TryUpdateModel(menu);
            int siteGuid = GetSiteGuid();

            try
            {

                //Update Menu
                SCSService.Menu me = Models.ConfigModel.GetMenuByID(menu.MenuId);
                me.MenuName = menu.MenuName;
                me.MenuText = menu.MenuText;
                me.Images = menu.Images;
                me.LanguagesID = menu.LanguagesID??1;
                if (menu.SortOrder != null)
                {
                    me.SortOrder = menu.SortOrder;
                }

                me.MenuUrl = menu.MenuUrl;
                if (menu.Active != null)
                {
                    me.MenuStatus = menu.Active==true?(byte)1:(byte)0;
                }

                me.SiteGuid = DefaultSiteGuidGetter();

                //Call Update method
                Models.ConfigModel.UpdateMenu(me);

                ViewData["Result"] = "Update Menu Success!";

            }
            catch
            {
                return View("", new Models.Collection.ArticleCategoryCollection());
            }
            return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/AdvantageSetting/ListMenu/");
        }

        public List<Menu> GetListMenuDropBasic(string MenuName, string MenuText, string MenuUrl, int? PartnerMenuId, int? MenuStatus, int? SortOrder, int? TypeMenuID, int? id, int LanguagesID, int siteGuid)
        {
            List<Menu> sb = new List<Menu>();
            return ListMenuDropBasic(MenuName, MenuText, MenuUrl, PartnerMenuId, MenuStatus, SortOrder,TypeMenuID, ref sb, id, true, LanguagesID, siteGuid);
        }

        public List<Menu> ListMenuDropBasic(string MenuName, string MenuText, string MenuUrl, int? PartnerMenuId, int? MenuStatus, int? SortOrder, int? TypeMenuID, ref List<Menu> sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Menu> listcate = Models.ConfigModel.GetListMenuByParentIDSearch(id, LanguagesID, siteGuid, MenuName, MenuText, MenuUrl, MenuStatus, SortOrder, TypeMenuID);

            foreach (var item in listcate)
            {
                if (!root)
                {
                    item.MenuText = Models.ConfigModel.GetMenuByID((int)item.PartnerMenuId).MenuText + ">>" + item.MenuText;

                    Menu ac = Models.ConfigModel.GetMenuByID((int)id);
                    foreach (var itemStr in sb)
                    {
                        if (itemStr.MenuId == ac.MenuId)
                        {
                            if (itemStr.MenuText.Contains(">>"))
                            {
                                int laststr = itemStr.MenuText.LastIndexOf(">>") + 2;
                                string addStr = itemStr.MenuText.Substring(0, laststr);
                                item.MenuText = addStr + item.MenuText;
                            }
                        }
                    }
                }


                sb.Add(item);
                List<SCSService.Menu> listChild = Models.ConfigModel.GetListMenuByParentIDSearch(item.MenuId, LanguagesID, siteGuid, MenuName, MenuText, MenuUrl, MenuStatus, SortOrder, TypeMenuID);
                if (listChild.Count() > 0)
                {
                    ListMenuDropBasic(MenuName, MenuText, MenuUrl, PartnerMenuId, MenuStatus, SortOrder, TypeMenuID, ref sb, item.MenuId, false, LanguagesID, siteGuid);
                }

            }

            return sb;
        }

        public StringBuilder GetListMenuBuilder(int? id, int LanguageID, int siteGuid)
        {
            StringBuilder sb = new StringBuilder();
            return ListMenuBuilder(ref sb, id, true, LanguageID, siteGuid);
        }

        public StringBuilder ListMenuBuilder(ref StringBuilder sb, int? id, bool root, int LanguagesID, int siteGuid)
        {
            List<SCSService.Menu> listcate = Models.ConfigModel.GetListMenuByParentIDSearch(id, LanguagesID, siteGuid,null,null,null,null,null,null);
            if (root)
            {
                sb.Append("<ul id='navigation'>" + "List Menu");
            }
            else
            {
                sb.Append("<ul>");
            }

            foreach (var item in listcate)
            {
                sb.Append("<li><a href='/" + siteGuid + "/" + StockModel.GetLanguageByID(LanguagesID).countryCode + "/AdvantageSetting/EditMenu/" + item.MenuId + "'>" + item.MenuText + "</a>");
                List<SCSService.Menu> listChild = Models.ConfigModel.GetListMenuByParentIDSearch(item.MenuId, LanguagesID, siteGuid, null, null, null, null, null, null);
                if (listChild.Count() > 0)
                {
                    ListMenuBuilder(ref sb, item.MenuId, false, LanguagesID, siteGuid);
                }
                sb.Append("</li>");
            }
            sb.Append("</ul>");

            return sb;
        }

        public ActionResult ChangeStatusMenu(int? id, int? proid)
        {
            Models.ConfigModel.UpdateStatusMenu(id, (byte)proid);
            string outStr = "" + proid;
            return Json(outStr);
        }

        public ActionResult UdpateSortIndex(int? id, int? proid)
        {
            Models.ConfigModel.UpdateSortOrderMenu(id, proid);
            string result = "" + proid;
            return Json(result);
        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.MenuViewModels> viewData, string sortField)
        {

            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.MenuViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        public static SelectList SetOrder(int langauesID, int siteGuid)
        {

            int count = Models.ConfigModel.GetCountMenu(langauesID, siteGuid);
            var tp = new List<string> { };
            for (int i = 1; i < (count + 1); i++)
            {
                tp.Add("" + i);
            }
            return new SelectList(tp);
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListMenu(string MenuName, string MenuText, int? SortOrder, byte? MenuStatus, string MenuUrl)
        {
            int currentPage = 1;
            int pageSize = 20;
            string sortField = "SortOrder";
            string sortDirection = "Asc";

            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;

            ViewData["ListMenu"] = GetListMenuBuilder(null, LanguageID, siteGuid);
            ViewData["SetOrder"] = SetOrder(LanguageID, siteGuid);

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListMenu(MenuName, MenuText, SortOrder, MenuStatus, MenuUrl, currentPage, pageSize, sortField, sortDirection, null, siteGuid);


        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListMenu(string MenuName, string MenuText, int? SortOrder, byte? MenuStatus, string MenuUrl, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }

            if (pageSize == null)
            {
                pageSize = 20;
            }

            if (siteGuid == null)
            {
                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;
            ViewData["ListMenu"] = GetListMenuBuilder(null, LanguageID, (int)siteGuid);
            ViewData["SetOrder"] = SetOrder(LanguageID, (int)siteGuid);

            var query = GetListMenuDropBasic(MenuName, MenuText, MenuUrl, null, MenuStatus, SortOrder, null, null, LanguageID, (int)siteGuid).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Menu), "Menu");
                var sortExpression = Expression.Lambda<Func<Menu, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }

            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Menu>();

            // Set up our ViewModel
            var viewModel = new MenuViewModels
            {
                MenuList = result,
                MenuName = MenuName,
                MenuText = MenuText,
                MenuUrl = MenuUrl,
                MenuStatus = MenuStatus,
                SortOrder = SortOrder
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }

        public ActionResult DeleteMenu(int id, string returnUrl)
        {

            Models.ConfigModel.DeleteMenu(id);
            ViewData["Result"] = "Delete success!";
           
            return Redirect(returnUrl);
        }
        #endregion

        #region "Metadata"
        
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult CreateMetadata()
        {
            var meta = new Models.Collection.MetadataCollection();
            int siteGuid = GetSiteGuid();

            ViewData["ListPage"] = new SelectList(Models.ConfigModel.GetListPageInWebsite(siteGuid), "PageID", "PageName");
            ViewData["IsAdd"] = true;

           
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailMetadata", meta);   //Return meta Detail
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveAddMetadata(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            var metacollection = new Models.Collection.MetadataCollection();
            TryUpdateModel(metacollection);
            int metaID = 0;
            try
            {
                
                    //Create Metadata
                    SCSService.Config_Metadata meta = new Config_Metadata();
                    meta.MetaTitle = metacollection.MetaTitle;
                    meta.MetaKeywords = metacollection.MetaKeywords;
                    meta.MetaDescription = metacollection.MetaDescription;
                    meta.PageID = metacollection.PageID;
                    meta.siteGuid = GetSiteGuid();
                    meta.Note = metacollection.Note;
                    meta.MetaPoweredBy = metacollection.MetaPoweredBy;
                    meta.MetaDcCreator = metacollection.MetaDcCreator;
                    meta.MetaAuthor = metacollection.MetaAuthor;
                    meta.MetaRobots = metacollection.MetaRobots;
                    meta.MenuId = metacollection.MenuId;
                    meta.Param = metacollection.Param;
                    meta.LanguagesID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
                    meta.MetaDctermsCreated = metacollection.MetaDctermsCreated;
                    meta.MetaDcctermsModified = metacollection.MetaDcctermsModified;
                    meta.RevisitAfter = metacollection.RevisitAfter;
                    meta.DatePublication = metacollection.DatePublication;
                    meta.Homepage = metacollection.Homepage;
                    meta.DcLanguage = metacollection.DcLanguage;

                    metaID = Models.ConfigModel.CreateMetadata(meta);

                  
                    ViewData["Result"] = "Create Metadata Success!";

                    return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/AdvantageSetting/ListMetadata");
                

            }
            catch
            {
                return View("DetailMetadata", new Models.Collection.MetadataCollection());     //return Detail Article
            }

        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult EditMetadata(int id)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            int siteGuid = GetSiteGuid();

            var meta = Models.ConfigModel.GetMetadataByID(id);
            var metaCollection = new Models.Collection.MetadataCollection();

            metaCollection.MetaTitle = meta.MetaTitle;
            metaCollection.MetaKeywords = meta.MetaKeywords;
            metaCollection.MetaDescription = meta.MetaDescription;
            metaCollection.PageID = meta.PageID;
            metaCollection.siteGuid = GetSiteGuid();
            metaCollection.Note = meta.Note;
            metaCollection.MetaPoweredBy = meta.MetaPoweredBy;
            metaCollection.MetaDcCreator = meta.MetaDcCreator;
            metaCollection.MetaAuthor = meta.MetaAuthor;
            metaCollection.MetaRobots = meta.MetaRobots;
            metaCollection.MenuId = meta.MenuId;
            metaCollection.Param = meta.Param;
            metaCollection.LanguagesID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            metaCollection.MetaDctermsCreated = meta.MetaDctermsCreated;
            metaCollection.MetaDcctermsModified = meta.MetaDcctermsModified;
            metaCollection.RevisitAfter = meta.RevisitAfter;
            metaCollection.DatePublication = meta.DatePublication;
            metaCollection.Homepage = meta.Homepage;
            metaCollection.DcLanguage = meta.DcLanguage;
            metaCollection.MetaID = meta.MetaID;

            ViewData["ListPage"] = new SelectList(Models.ConfigModel.GetListPageInWebsite(siteGuid), "PageID", "PageName");
            ViewData["IsAdd"] = false;

            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View("DetailMetadata", metaCollection);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult SaveEditMetadata(FormCollection collection)
        {
            BaseService baseSvc = new BaseService();
            var metacollection = new Models.Collection.MetadataCollection();
            TryUpdateModel(metacollection);
            int siteGuid = GetSiteGuid();

            try
            {

                //Update Metadata
                var meta = Models.ConfigModel.GetMetadataByID(metacollection.MetaID);
                meta.MetaTitle = metacollection.MetaTitle;
                meta.MetaKeywords = metacollection.MetaKeywords;
                meta.MetaDescription = metacollection.MetaDescription;
                meta.PageID = metacollection.PageID;
                meta.siteGuid = GetSiteGuid();
                meta.Note = metacollection.Note;
                meta.MetaPoweredBy = metacollection.MetaPoweredBy;
                meta.MetaDcCreator = metacollection.MetaDcCreator;
                meta.MetaAuthor = metacollection.MetaAuthor;
                meta.MetaRobots = metacollection.MetaRobots;
                meta.MenuId = metacollection.MenuId;
                meta.Param = metacollection.Param;
                meta.LanguagesID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
                meta.MetaDctermsCreated = metacollection.MetaDctermsCreated;
                meta.MetaDcctermsModified = metacollection.MetaDcctermsModified;
                meta.RevisitAfter = metacollection.RevisitAfter;
                meta.DatePublication = metacollection.DatePublication;
                meta.Homepage = metacollection.Homepage;
                meta.DcLanguage = metacollection.DcLanguage;

                //Call Update method
                Models.ConfigModel.UpdateMetadata(meta);

                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/AdvantageSetting/ListMetadata");
            }
            catch
            {
                return View("DetailMetadata", new Models.Collection.MetadataCollection());
            }

        }

        public static string GetGridThClass(ViewDataDictionary<SCS.Core.ViewModels.ListMetadataViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] != sortField)
                return "";

            if ((string)viewData["SortDirection"] == "Asc")
                return "asc";

            return "desc";
        }

        public static string GetGridThOnClick(ViewDataDictionary<SCS.Core.ViewModels.ListMetadataViewModels> viewData, string sortField)
        {
            if ((string)viewData["SortField"] == sortField && (string)viewData["SortDirection"] == "Asc")
                return "sort('" + sortField + "', 'Desc');";

            return "sort('" + sortField + "', 'Asc');";
        }

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult ListMetadata(int? id, string TitleSearch)
        {
            //Id đầu vào là cateId
            int currentPage = 1;
            int pageSize = 20;
            string sortField = "MetaID";
            string sortDirection = "Asc";

            int siteGuid = GetSiteGuid();

            ViewData["currentPage"] = currentPage;
            ViewData["pageSize"] = pageSize;


            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return ListMetadata(TitleSearch, currentPage, pageSize, sortField, sortDirection, null, id, siteGuid);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult ListMetadata(string TitleSearch, int? currentPage, int? pageSize, string sortField, string sortDirection, string gridAction, int? id, int? siteGuid)
        {
            int LanguageID = StockModel.GetLanguageIDByCountryCode(DefaultLanguageGetter());
            //id đầu vào là cateId
            if (gridAction == "PageSizeChanged" || gridAction == "Sorted")
                currentPage = 1;

            if (currentPage == null && gridAction == "CurrentPageChanged")
            {
                string strCurrentPage = Request.Form.Get("quickPage").Replace(",", "");
                currentPage = int.Parse(strCurrentPage);
            }
            else if (currentPage == null)
            {
                currentPage = 1;
            }


            if (pageSize == null)
            {
                pageSize = 20;
            }

            if (siteGuid == null)
            {

                siteGuid = GetSiteGuid();
            }

            ViewData["currentPage"] = currentPage;


            var query = Models.ConfigModel.GetListMetadata(TitleSearch, (int)siteGuid, LanguageID).AsQueryable();
            int totalRows = query.Count();

            if (!String.IsNullOrEmpty(sortField))
            {
                var param = Expression.Parameter(typeof(Config_Metadata), "Config_Metadata");
                var sortExpression = Expression.Lambda<Func<Config_Metadata, object>>
                                        (Expression.Convert(Expression.Property(param, sortField), typeof(object)), param);

                if (sortDirection == "Asc")
                    query = query.OrderBy(sortExpression);
                else
                    query = query.OrderByDescending(sortExpression);
            }

            int totalPages = (int)Math.Ceiling((double)totalRows / (double)pageSize);
            if (totalPages != 1)
            {
                //paging
                query = query.Skip(((int)currentPage - 1) * (int)pageSize)
                                .Take((int)pageSize);
            }


            UpdateSorterViewData(sortField, sortDirection);
            UpdatePagerViewData(totalPages, totalRows, (int)currentPage, (int)pageSize);

            var result = query.ToList();

            if (totalRows == 0)
                result = new List<SCSService.Config_Metadata>();


            // Set up our ViewModel
            var viewModel = new ListMetadataViewModels
            {
                MetadataItem = result,
                TitleSearch = TitleSearch
            };

            // Return the view
            if (Session["UserID"] == null)
            {
                return Redirect("/" + DefaultSiteGuidGetter() + "/" + DefaultLanguageGetter() + "/User/SignIn");
            }
            else
                return View(viewModel);
        }

        public ActionResult DeleteMetadata(int id, string returnUrl)
        {
            Models.ConfigModel.DeleteMetadata(id);
            ViewData["Result"] = "Delete success!";

            return Redirect(returnUrl);
        }
        #endregion      
    }
}
